package com.resource.util.page;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import org.apache.logging.log4j.util.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Data
@ToString
public class PageParam {

    private static final String SEPARATOR = ",";
    private long current = 1L;
    private long size = 10L;
    private List<String> sort = new ArrayList();
    private List<OrderItem> orders = new ArrayList();

    public PageParam() {
    }

    public <T> Page<T> toMybaitsPage() {
        Page<T> page = new Page(this.current, this.size);
        page.setOrders(this.orders());
        return page;
    }

    @ApiModelProperty(
            value = "当前页1开始",
            name = "current"
    )
    public long getCurrent() {
        return this.current;
    }

    @ApiModelProperty(
            value = "分页大小",
            name = "size"
    )
    public long getSize() {
        return this.size;
    }

    @ApiModelProperty(
            value = "排序字段如 id,desc",
            name = "sort",
            example = "id,asc",
            dataType = "string"
    )

    public void setCurrent(long current) {
        this.current = current;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public void setSort(List<String> sort) {
        this.sort = sort;
    }

    public String toString() {
        return "MPage(current=" + this.getCurrent() + ", size=" + this.getSize()  + ", sort=" + this.getSort() + ")";
    }

    public List<OrderItem> orders() {
        if(!getSort().isEmpty()) {
            orders=by(getSort());
            sort.clear();
        }
        return orders;
    }

    /**
     * 此方法在 orders() 调用后返回空列表
     * @return
     */
    public	List<String> getSort(){
        if(sort==null) {
            sort=new ArrayList<>();
        }
        return sort;
    }

    public static List<OrderItem> by(Iterable<String> sorts) {
        List<OrderItem> orderItems = new ArrayList<>();
        for (String sortParameterValue : merge(sorts)) {
            String[] split = StrUtil.split(sortParameterValue, SEPARATOR);
            String column=null;
            boolean asc=true;
            if (ArrayUtil.length(split) == 2 ) {
                column = split[0];
                String order = split[1];
                asc=!"desc".equalsIgnoreCase(order);
            }else if (	ArrayUtil.length(split) == 1){
                column = split[0];
            }else {
                continue;
            }
            column=checkColumn(column);
            if(StrUtil.isNotBlank(column)) {
                if (asc) {
                    orderItems.add(OrderItem.asc(column));
                } else {
                    orderItems.add(OrderItem.desc(column));
                }
            }

        }
        return orderItems;
    }
    /**
     * 合并  避免   colname,order 被分开
     * @param sorts
     * @return
     */
    private static List<String> merge(Iterable<String> sorts) {
        List<String> list1=new ArrayList<>();
        for (String s :sorts) {
            if(Strings.isBlank(s)) {
                continue;
            }
            s=s.trim();
            if("asc".equalsIgnoreCase(s)) {
                //忽略
            }else if("desc".equalsIgnoreCase(s) && !list1.isEmpty()) {
                String last = list1.get(list1.size()-1);
                if(!last.contains(SEPARATOR)) {
                    list1.set(list1.size()-1, last+SEPARATOR+"desc");
                }
                //忽略
            }else {
                list1.add(s);
            }
        }
        return list1;
    }

    private static String checkColumn(String column) {
        if(Strings.isBlank(column)) {
            return null;
        }
        String ori = column.trim().replace("`", "");
        if(ori.startsWith(".") || ori.endsWith(".") || ori.isEmpty()) {
            return null;
        }
        column=ori.replace("_", "");
        column=ReUtil.replaceAll(column, Pattern.compile(".", Pattern.LITERAL), " ").trim();

        if( ReUtil.isMatch(".*[\\pP‘’“”]+.*", column)) {
            return null;//含有标点符号
        }
        String[] arr = column.split("\\s");
        if(!(ArrayUtil.length(arr) ==1 || (ArrayUtil.length(arr) ==2 && ori.contains(".")))) {
            return null;//不止一个组分
        }
        column=ori.replace("`", "");
        if(column.contains(".")) {
            arr=column.split("\\.");
            return "`"+arr[0]+"`.`"+arr[1]+"`";
        }else {
            return "`"+column+"`";
        }
    }
}
